package com.ruoyi.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.MaterialLogRequest;
import com.ruoyi.common.core.domain.entity.CommonEntity;
import com.ruoyi.common.core.page.PageList;
import com.ruoyi.common.core.page.PageQuery;
import com.ruoyi.common.core.page.PageUtil;
import com.ruoyi.common.core.page.ResultEntity;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.MaterialEntity;
import com.ruoyi.system.domain.MaterialLogEntity;
import com.ruoyi.system.domain.MaterialLogGroupResponse;
import com.ruoyi.system.domain.MaterialReportEntity;
import com.ruoyi.system.domain.vo.MaterialLogEntityResponseVO;
import com.ruoyi.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;


@Api(tags = "物料管理")
@RestController
@RequestMapping("/material")
public class MaterialLogController {

    @Autowired
    private MaterialService materialService;

    @Autowired
    private MaterialLogService materialLogService;

    @Autowired
    private MaterialReportService materialReportService;

    @Autowired
    private MaterialHistoryService materialHistoryService;

    @Autowired
    private MaterialSyncService originalSyncService;






    @GetMapping("/font/in/group")
    @ApiOperation(value = "首页获取入库记录")
    public ResultEntity fontListInGroup(){

        var ans = new HashMap<>();
        ans.put("钢板", "MC0101");
        ans.put("钢管", "MC0103");
        ans.put("钢绞线", "MC0104");
        ans.put("钢丝绳、钢丝", "MC0105");
        ans.put("建筑钢筋", "MC0106");
        ans.put("型钢", "MC0107");
        ans.put("其他钢材制品", "MC0110");


        var tmpAns = new ArrayList<MaterialLogGroupResponse>();

        AtomicInteger i = new AtomicInteger();

        ans.forEach((key, value) -> {

            var oneTmpAns = new MaterialLogGroupResponse();
            oneTmpAns.setMaterialCode(value.toString());
            oneTmpAns.setMaterialName(key.toString());
            oneTmpAns.setNum(i.get());
            oneTmpAns.setMaterialNum(materialLogService.countMaterialInNum(value.toString()));

           tmpAns.add(oneTmpAns);
            i.set(i.get() + 1);
        });



        return ResultEntity.createSuccess(tmpAns);
    }



    @GetMapping("/font/in/list")
    @ApiOperation(value = "首页获取入库记录")
    public ResultEntity fontListIn(@RequestParam(value = "", required=false) String materialCode){

        var nowTimeFormat =  LocalDateTime.now();

        LocalDateTime halfMonthAgo = nowTimeFormat.minus(30, ChronoUnit.DAYS);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 格式化日期时间
        String formattedDateTime = halfMonthAgo.format(formatter);

        var requestParams = new LambdaQueryWrapper<MaterialLogEntity>()
                .eq(MaterialLogEntity::getDelFlag,0)
                .eq(MaterialLogEntity::getIsIn, 1);

        if (materialCode != null && !materialCode.isEmpty()) {
            requestParams = requestParams.like(MaterialLogEntity::getMaterialCode, materialCode);
        }


        var tmpDatas =  materialLogService.list(requestParams);


        var  additionMaterialLog = new ArrayList<MaterialLogEntityResponseVO>();

        var  additionMaterialLogId = new ArrayList<String>();


        for ( var item :  tmpDatas) {

            var tmpAddition = new MaterialLogEntityResponseVO();

            BeanUtils.copyProperties(item, tmpAddition);
            additionMaterialLogId.add(item.getId());

            additionMaterialLog.add(tmpAddition);

        }

        var materialReportList = materialReportService.getMaterialLogReports(additionMaterialLogId);

        var materialReportSet =  new HashMap<String, MaterialReportEntity>();

        for ( var item : materialReportList) {
            materialReportSet.put(item.getMaterialLogId().toString(), item);
        }

        for ( var item :  additionMaterialLog) {
            if (materialReportSet.containsKey(item.getId())) {
                item.setReportLink(materialReportSet.get(item.getId()).getReportLink());
                item.setChecked(true);
            } else {
                item.setChecked(false);
                item.setReportLink("");
            }
        }


        return ResultEntity.createSuccess(additionMaterialLog);
    }



    @GetMapping("/in/list")
    @ApiOperation(value = "获取入库记录表")
    public ResultEntity listIn(MaterialLogRequest pageQuery){
        PageUtil.startPage(pageQuery);

        var requestParams = new LambdaQueryWrapper<MaterialLogEntity>()
                .eq(MaterialLogEntity::getDelFlag,0)
                .eq(MaterialLogEntity::getIsIn, 1);

        requestParams.like(MaterialLogEntity::getMaterialCode, "MC01");

        if (pageQuery.getMaterialCode() != null) {
            requestParams.eq(MaterialLogEntity::getMaterialCode, pageQuery.getMaterialCode());
        }

        requestParams = requestParams.orderByDesc(CommonEntity::getUpdateTime);

        var responseData = PageUtil.getPageList(materialLogService.list(requestParams));

        var  additionMaterialLog = new ArrayList<MaterialLogEntityResponseVO>();

        var  additionMaterialLogId = new ArrayList<String>();


        for ( var item :  responseData.getData()) {

            var tmpAddition = new MaterialLogEntityResponseVO();

            BeanUtils.copyProperties(item, tmpAddition);
            additionMaterialLogId.add(item.getId());

            additionMaterialLog.add(tmpAddition);

        }

        var materialReportList = materialReportService.getMaterialLogReports(additionMaterialLogId);

        var materialReportSet =  new HashMap<String, MaterialReportEntity>();

        for ( var item : materialReportList) {
            materialReportSet.put(item.getMaterialLogId().toString(), item);
        }

        for ( var item :  additionMaterialLog) {
            if (materialReportSet.containsKey(item.getId())) {
                item.setReportLink(materialReportSet.get(item.getId()).getReportLink());
                item.setChecked(true);
            } else {
                item.setChecked(false);
                item.setReportLink("");
            }
        }


        var ans = new PageList<MaterialLogEntityResponseVO>();


        BeanUtils.copyProperties(responseData, ans);

        ans.setData(additionMaterialLog);



        //  不要补充下 检验单中 添加的链接 2024-10-10
        return ResultEntity.createSuccess(ans);
    }


    @GetMapping("/sync/material_record")
    @ApiOperation(value = "同步材料进入库记录")
    @Transactional
    public ResultEntity syncMaterialRecord(){

        PageQuery page = new PageQuery();
        page.setPageNo(1);
        page.setPageSize(200);
        return ResultEntity.createSuccess(originalSyncService.getAllAuditBill("2024-10-10 00:00:00",
                "CRCC1101GL0220240002", page));
    }

    @GetMapping("/sync/material_sync_log")
    @ApiOperation(value = "同步材料进入库记录")
    @Transactional
    public ResultEntity syncMaterialLogRecord(){

        PageQuery page = new PageQuery();
        page.setPageNo(1);
        page.setPageSize(200);
        return ResultEntity.createSuccess(originalSyncService.getAllMaterialLogRecord("2024-10-10 00:00:00",
                "CRCC1101GL0220240002", page));
    }

    @GetMapping("/sync/save_material_log_record")
    @ApiOperation(value = "同步材料进入库记录")
    @Transactional
    public ResultEntity saveMaterialRecordLog(){

        PageQuery page = new PageQuery();
        page.setPageNo(1);
        page.setPageSize(200);
        return ResultEntity.createSuccess(originalSyncService.getAllMaterialSave2Tab("2021-10-10 00:00:00","CRCC1101GL0220240002", page));
    }

    @PostMapping("/out/add")
    @ApiOperation(value = "添加出库记录")
    /*
     *  1.判断数量是否满足出库
     *  2. 减少数量
     *  添加出库记录
     *  只能添加不能修改
     * */
    public ResultEntity addOut(@RequestBody MaterialLogEntity params){
        params.setIsIn(2);

        // 不允许修改, 还能添加
        if (params.getId() != null && !params.getId().isEmpty()) {
            return ResultEntity.createError("-1", "出库记录不允许修改");
        }

        if (params.getMaterialCode() == null || params.getMaterialCode().isEmpty()) {
            return ResultEntity.createError("-1", "原材料不存在 {}");
        }

        var existMaterialEntity = materialService.getByCode(params.getMaterialCode());

        if (existMaterialEntity == null) {
            return ResultEntity.createError("-1", "原材料不存在: " + params.getMaterialCode());
        }

        if (existMaterialEntity.getActualCount() < params.getActualCount()) {
            return ResultEntity.createError("-1", "实际数量不足");
        }

        return ResultEntity.createSuccess(materialLogService.addMaterialLog(params));
    }

    @GetMapping("/out/list")
    @ApiOperation(value = "获取出库记录表")
    public ResultEntity listOut(MaterialLogRequest pageQuery){
        var requestParams = new LambdaQueryWrapper<MaterialLogEntity>()
                .eq(MaterialLogEntity::getDelFlag,0)
                .eq(MaterialLogEntity::getIsIn, 2);

        if (pageQuery.getMaterialCode() != null) {
            requestParams.eq(MaterialLogEntity::getMaterialCode, pageQuery.getMaterialCode());
        }

        PageUtil.startPage(pageQuery);
        return ResultEntity.createSuccess(PageUtil.getPageList(materialLogService.list(requestParams)));
    }


    @GetMapping("/log/delete")
    @ApiOperation(value = "删除材料进出库记录")
    public ResultEntity deleteOutbound(@RequestParam("id") String id){
        // 更新库存量
        return ResultEntity.createSuccess(materialLogService.deleteMaterialLog(id));
    }

    @PostMapping("/material/add")
    @ApiOperation(value = "材料入库")
    public ResultEntity addMaterial(@RequestBody MaterialEntity params){

        params.setCreateBy(SecurityUtils.getLoginUser().getUser().getId());
        params.setUpdateBy(SecurityUtils.getLoginUser().getUser().getId());
        params.setCreator(SecurityUtils.getLoginUser().getUser().getName());
        materialService.saveOrUpdate(params);
        return ResultEntity.createSuccess();
    }

    /*
     *  1.判断数量是否满足出库
     *  2. 减少数量
     *  添加出库记录
     * */
    @PostMapping("/in/add")
    @ApiOperation(value = "材料入库")
    @Transactional
    public ResultEntity addIn(@RequestBody MaterialLogEntity params){

        params.setIsIn(1);
        return ResultEntity.createSuccess(materialLogService.addMaterialLog(params));
    }

}